package com.itcodai.course16.controller;

import com.itcodai.course16.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户Controller
 * @author shengwu ni
 */
@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {

    /**
     * 用户登录接口
     * @param user user
     * @param request request
     * @return string
     */
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {

        // 根据用户名和密码创建token
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        // 获取subject认证主体
        Subject subject = SecurityUtils.getSubject();
        String sid = (String) subject.getSession().getId();
        if(null != sid){
            try{
                // 开始认证，这一步会跳到我们自定义的realm中
                subject.login(token);
                request.getSession().setAttribute("user", user);
                return sid;
            }catch(Exception e){
                e.printStackTrace();
                request.getSession().setAttribute("user", user);
                request.setAttribute("error", "用户名或密码错误！");
                return "login";
            }
        }else {
            return "login";
        }

    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "login";
    }

    /**
     * 身份认证测试接口
     * @param request
     * @return
     */
    @RequestMapping("/admin")
    public String admin(HttpServletRequest request) {
        Object user = request.getSession().getAttribute("user");
        return "success";
    }

    /**
     * 角色认证测试接口
     * @param request
     * @return
     */
    @RequestMapping("/student")
    public String student(HttpServletRequest request) {
        return "success";
    }

    /**
     * 权限认证测试接口
     * @param request
     * @return
     */
    @RequestMapping("/teacher")
    public String teacher(HttpServletRequest request) {
        return "success";
    }

    /**
     * 1.过滤器：如果权限信息不匹配setUnauthorizedUrl地址
     * 2.注解：如果权限信息不匹配，抛出异常 AuthorizationException
     */
    //使用shiro鉴权
    //@RequiresPermissions() 访问此方法必须具备的权限
    //@RequiresRoles()   访问此方法必须具备的角色
    @RequiresPermissions("student:create")
    @RequestMapping("/home")
    public String home() {
        return "访问个人主页成功";
    }
}
